<?php
namespace admin\controllers;
use admin\controllers\common\BaseController;
use common\component\AdCommon;
use common\component\BaseWebController;
use common\component\Common;
use common\component\MenuHelper;
use common\component\Tree;
use common\models\Admin;
use common\models\AdminChangePass;
use common\models\FIRM;
use common\models\RegionShareSet;
use common\models\User;

use common\service\DataService;
use common\service\TreeService;
use common\service\UserService;
use Faker\Provider\Base;
use Yii;
use yii\filters\AccessControl;
use yii\helpers\ArrayHelper;


/**
 * Site controller
 */

class UserController extends BaseController
{

    public $enableCsrfValidation = false;
    /**
     * Displays homepage.
     * @return mixed
     */
    public $modelClass = 'common\models\Admin';

    //首页
    public function actionIndex()
    {
        $this->getView()->title = "用户中心";
        return $this->render('index');
    }

    //用户列表
    public function actionList()
    {
        $uid = $this->getUid();
        $user_list = UserService::getUserList();
        $this->_data['user_list'] = $user_list;
        return $this->view();
    }

    /**
     * 获取组织结构图数据
     */
    public function actionGet_map()
    {
        // 尝试从缓存中取回 $data
        $cache = Yii::$app->cache;

        //如果是更新缓存
        if($_GET['type'] == 'update')
        {
            //删除缓存
            $cache->delete('int_map');

            //获取组织列表
            $list = UserService::getSonUserList(15803);
            $under = UserService::getUserList(15803);
            $ids = ArrayHelper::getColumn($under,'id');

            $arr = [];
            foreach($list as $key=>$val)
            {
                $arr[$key] = $val;
                $arr[$key]['text'] = $val['name'];

                if(in_array($val['id'],$ids)){
                    $arr[$key]['collapsed'] = false;
                }else{
                    $arr[$key]['collapsed'] = true;
                }
            }

            $arr[15803]['int_id'] = 0;

            //树形结构展示
            $tree = TreeService::makeTree($arr,['parent_id'=>'int_id']);
            $cache->set('int_map', $tree, CACHE_TIME_OUT);

        }else{

            $data = $cache->get('int_map');
            if($data === false){
                //获取组织列表
                $list = UserService::getSonUserList(15803);
                $under = UserService::getUserList(15803);
                $ids = ArrayHelper::getColumn($under,'id');

                $arr = [];
                foreach($list as $key=>$val)
                {
                    $arr[$key] = $val;
                    $arr[$key]['text'] = $val['name'];

                    if(in_array($val['id'],$ids)){
                        $arr[$key]['collapsed'] = false;
                    }else{
                        $arr[$key]['collapsed'] = true;
                    }
                }

                $arr[15803]['int_id'] = 0;

                //树形结构展示
                $tree = TreeService::makeTree($arr,['parent_id'=>'int_id']);
                $cache->set('int_map', $tree, CACHE_TIME_OUT);
            }
        }

        $data = $cache->get('int_map');
        return $this->renderJSON($data,'数据返回成功',200);
    }

    /**
     * excel导出返佣记录
     */
    public function actionExport()
    {
        $post = $this->get();

        $user_list = User::find()->indexBy('id')->asArray()->all();
        $data = new DataService(new User);
        $condition = '1=1';

        if(!empty($post['start_time']))
        {
            $condition .= ' and register_time >= "'.strtotime($post['start_time'].' 00:00:00').'"';
        }

        if(!empty($post['end_time']))
        {
            $condition .= ' and register_time < "'.strtotime($post['end_time'].' 23:59:59').'"';
        }

        if(!empty($post['keyword']))
        {
            if(is_numeric($post['keyword'])){
                $condition .= ' and ( id = "'.$post['keyword'].'" or firm_id = "'.$post['keyword'].'") ';
            }else{
                $condition .= ' and name like "%'.$post['keyword'].'%"';
            }
        }

        //如果有推荐人ID
        if(!empty($post['int_id'])){
            //获取所有用户
            $list = UserService::getUserList();
            $new_user_list = UserService::getSonTree($post['int_id'],$list);
            if(!empty($new_user_list)){
                $inv_firm_ids = ArrayHelper::getColumn($new_user_list,'id');
                $condition .= ' and id in('.join(',',$inv_firm_ids).') ';
            }else{
                $condition .= ' and id < 0 ';
            }
        }

        //数据返回
        $res = $data->getDataByCondition($condition,100000,-1,'','register_time desc',false);

        //数据重新拼接返回
        $arr = [];
        foreach($res['data'] as $key=>$val)
        {
            $arr[$key]['name'] = $val['name'];
            $arr[$key]['firm_id'] = $val['firm_id'] == 0 ? '未绑定' : $val['firm_id'];
            $arr[$key]['phone'] = "\t".$val['phone'];
            $arr[$key]['card_code'] = "\t".$val['card_code'];
            $arr[$key]['int_id'] = $user_list[$val['int_id']]['name'];
            $arr[$key]['int_name'] = "\t".$user_list[$val['int_id']]['phone'];
            $arr[$key]['account_type'] = UserService::USER_TYPE_LIST[$val['account_type']];
            $arr[$key]['register_time'] = date('Y-m-d H:i:s',$val['register_time']);
        }

        //执行数据导出
        $columnArr = array('用户名','交易商ID','手机号码','身份证号','推荐人','推荐人手机号码','账户类型','注册时间');
        $file = '用户信息列表'.date('Ymd',time()).'.csv';
        Common::exportCsv($columnArr, $arr, $file);

    }

    //获取用户数据列表
    public function actionGet_list_data()
    {
        if($this->_isAjax() || $this->_isPost())
        {
            $post = $this->post();

            $limit = Yii::$app->request->post('limit',10);
            $page = Yii::$app->request->post('page',0);

            $user_list = User::find()->select('id,name')->indexBy('id')->asArray()->all();

            $data = new DataService(new User);

            $condition = '1=1';

            if(!empty($post['start_time']))
            {
                $condition .= ' and register_time >= "'.strtotime($post['start_time'].' 00:00:00').'"';
            }

            if(!empty($post['end_time']))
            {
                $condition .= ' and register_time < "'.strtotime($post['end_time'].' 23:59:59').'"';
            }

            if(!empty($post['keyword']))
            {
                if(is_numeric($post['keyword'])){
                    $condition .= ' and ( id = "'.$post['keyword'].'" or firm_id = "'.$post['keyword'].'") ';
                }else{
                    $condition .= ' and name like "%'.$post['keyword'].'%"';
                }
            }

            //如果有推荐人ID
            if(!empty($post['int_id'])){
                //获取所有用户
                $list = UserService::getUserList();
                $new_user_list = UserService::getSonTree($post['int_id'],$list);
                if(!empty($new_user_list)){
                    $inv_firm_ids = ArrayHelper::getColumn($new_user_list,'id');
                    $condition .= ' and id in('.join(',',$inv_firm_ids).') ';
                }else{
                    $condition .= ' and id < 0 ';
                }
            }

            //数据返回
            $res = $data->getDataByCondition($condition,$limit,$page-1,'','register_time desc',true);

            //数据重新拼接返回
            $arr = [];
            foreach($res['data'] as $key=>$val)
            {
                $arr[$key] = $val;
                $arr[$key]['firm_id'] = $val['firm_id'] == 0 ? '未绑定' : $val['firm_id'];
                $arr[$key]['int_id'] = $user_list[$val['int_id']]['name'];
                $arr[$key]['account_type'] = UserService::USER_TYPE_LIST[$val['account_type']];
                $arr[$key]['register_time'] = date('Y-m-d H:i:s',$val['register_time']);
            }

            if($res){
                echo json_encode([
                    'code'=>0,
                    'count'=>$res['count'],
                    'data'=>$arr,
                    'extra'=>'',
                    'message'=>'获取数据成功'
                ]);
            }
        }
    }


    //用户详情页
    public function actionDetail(){

        $id = $this->get('id');
        if(!$id){
            echo "<script>alert('非法访问!');</script>";
            exit;
        }

        //获取用户信息
        $user = User::find()->where('id =:id',[':id'=>$id])->asArray()->one();
        $this->_data['user'] = $user;

        //如果用户有绑定交易商账号
        if($user['firm_id'] != 0)
        {
            $firm = FIRM::find()->where('FIRMID = :firm_id',[':firm_id'=>$user['firm_id']])->asArray()->one();
        }else{
            $firm = [];
        }

        $this->_data['int_users'] = User::find()->select(['id','phone','name'])->indexBy('id')->asArray()->all();
        $this->_data['firm'] = $firm;

        return $this->view();
    }


    //用户详情更新
    public function actionUpdate_info()
    {
        if($this->_isAjax() || $this->_isPost())
        {
            $post = $this->post();
            $id = $post['id'];
            $user = User::findOne($id);
            $user->attributes = $post;

            //判断是否存在循环推荐情况
            if(!empty($post['int_id']))
            {
                $int_user = User::findOne($post['int_id']);
                $result = UserService::CheckIntCode($int_user['phone'],$id);
                if(!$result){
                    return $this->renderJSON($int_user['phone'],'存在循环推荐情况,不能选择该推荐人',201);
                }
            }

            if(empty($post['firm_id']))
            {
                $user->firm_id = 0;
            }

            if(!empty($post['account_type']))
            {
                switch($post['account_type']){
                    case 1:
                        //如果是用户,则店铺ID和代理ID等于他的全都变为0
                        User::updateAll(
                            ['shopid'=>0,'pid'=>0],
                            ['or',['shopid'=>$id],['pid'=>$id]]
                        );
                        break;

                    //2表示门店
                    case 2:
                        $list = UserService::getUserList();
                        $user_list = UserService::getSonTree($id,$list);
                        $inv_firm_ids = ArrayHelper::getColumn($user_list,'id');

                        //名下所有递归用户,没有店铺的都归入该门店
                        User::updateAll(
                            ['shopid'=>$id],
                            ['and',['in','id',$inv_firm_ids],['shopid'=>0]]
                        );
                        break;

                    //3、4表示代理
                    case 3:
                    case 4:
                        $list = UserService::getUserList();
                        $user_list = UserService::getSonTree($id,$list);
                        $inv_firm_ids = ArrayHelper::getColumn($user_list,'id');

                        //名下所有递归用户,没有代理的都归入该代理
                        User::updateAll(
                            ['pid'=>$id],
                            ['and',['in','id',$inv_firm_ids],['pid'=>0]]
                        );
                        break;
                }
            }

            if($user->save()){
                return $this->renderJSON('','修改成功',200);
            }else{
                return $this->renderJSON($user->errors,'修改失败',201);
            }
        }
    }


    //个人信息
    public function actionInfo()
    {
        $uid = $this->getUid();
        $user = User::find()->where(['id'=>$uid])->asArray()->one();
        $this->_data['user'] = $user;

        //定义title
        $this->getView()->title = "用户信息";
        return $this->view();
    }

    //代理区域列表
    public function actionProxy_region_list()
    {
        //定义title
        $this->getView()->title = "代理区域列表";
        return $this->view();
        
    }

    //代理区域列表
    public function actionGet_region_list()
    {
        if($this->_isAjax() || $this->_isPost())
        {
            $post = $this->post();
            $limit = Yii::$app->request->post('limit', 10);
            $page = Yii::$app->request->post('page', 0);
            $condition = '1=1';
            if(!empty($post['keyword']))
            {
                if(is_numeric($post['keyword'])){
                    $condition .= ' and firm_id = "'.$post['keyword'].'" ';
                }else{
                    $condition .= ' and name like "%'.$post['keyword'].'%"';
                }
            }


            //数据返回
            $data = new DataService(new RegionShareSet());
            $res = $data->getDataByCondition($condition, $limit, $page - 1, '', 'uid desc', true);
            //数据重新拼接返回
            $arr = [];
            if ($res) {
                foreach ($res['data'] as $key => $val) {

                    $arr[$key] = $val;
                    $arr[$key]['status'] = $val['status'] == 1 ? '有效' : '无效';
                    $arr[$key]['addtime'] = date('Y-m-d H:i:s', $val['addtime']);
                    $arr[$key]['updatetime'] = $val['updatetime']>0?date('Y-m-d H:i:s', $val['updatetime']):'';

                }
            }
            return json_encode([
                'code'=>0,
                'count'=>$res['count'],
                'data'=>$arr,
                'message'=>'获取数据成功'
            ]);

        }

    }

    //编辑代理区域
    public function actionEdit_proxy_region()
    {
        $id = $this->get('id');
        $datas = RegionShareSet::find()->where('id=:id',[':id'=>$id])->asArray()->one();
        
        $proxyuser = User::find()->where('account_type>2')->asArray()->all();
        $datas['proxyuser'] = $proxyuser;
        if($this->_isAjax() && $this->_isPost()){
            $data = RegionShareSet::find()->where('id=:id',[':id'=>$id])->one();
            $post = $this->post();
            
            if($data['uid'] != $post['uid']){
                $check = RegionShareSet::find()->where('uid=:uid',[':uid'=>$post['uid']])->asArray()->one();
                if($check){
                    return json_encode(['status'=>-1,'msg'=>'该代理已经设置过区域','data'=>'']);
                }
                $user = User::findOne($post['uid']);
                $data->firm_id = $user['firm_id'];
                $data->name = $user['name'];
            }
            $data->uid = $post['uid'];
            $data->remark = $post['remark'];
            $data->status = $post['status'];
            $data->region = $post['region'];
            $data->card_code = $post['card_code'];
            $data->updatetime = time();
            if($data->save()){
                return $this->renderJSON('','编辑成功',200);
            }else{
                return $this->renderJSON($data->errors,'编辑失败',201);
            }
            
        }
        
        return $this->render('regionedit',$datas);
    }

    //添加代理区域
    public function actionAdd_proxy_region()
    {
        $proxyuser = User::find()->where('account_type>2')->asArray()->all();
        $datas['proxyuser'] = $proxyuser;
        if($this->_isAjax() && $this->_isPost()){

            $post = $this->post();

            $data = new RegionShareSet();
            $check = RegionShareSet::find()->where('uid=:uid',[':uid'=>$post['uid']])->asArray()->one();
            if($check){
                return json_encode(['status'=>-1,'msg'=>'该代理已经设置过区域','data'=>'']);
            }
            $user = User::findOne($post['uid']);
            $data->firm_id = $user['firm_id'];
            $data->name = $user['name'];
            $data->region = $post['region'];
            $data->uid = $post['uid'];
            $data->remark = $post['remark'];
            $data->status = $post['status'];
            $data->card_code = $post['card_code'];
            $data->addtime = time();
            if($data->save()){
                return $this->renderJSON('','添加成功',200);
            }else{
                return $this->renderJSON($data->errors,'添加失败',201);
            }

        }
        return $this->render('regionedit',$datas);
    }


    /**
     * 重置登录密码
     */
    public function actionChange()
    {
        if($this->_isAjax() || $this->_isPost())
        {
            $post = $this->post();
            $model = new AdminChangePass();
            $model->attributes = $post;
            $model->name = Yii::$app->user->identity->name;

            //验证
            if(!$model->validate()){
                $msg = AdCommon::getModelError($model);
                return $this->renderJSON([],$msg,-1);
            }

            //新密码加密
            $newpassword = Admin::encryption($post['newpassword'],Yii::$app->user->identity->code);
            $res = Admin::changepass($this->getUid(),$newpassword);

            if($res){
                return $this->renderJSON([],'密码重置成功',200);
            }

        }

        $this->getView()->title = "修改登录密码";
        return $this->render('change');
    }


}
